<template>
  <div class="o-aux-input">
    <Input
      v-model="value"
      :disabled="true"
      :placeholder="renderOpts.props.placeholder"
      :class="'align-' + align"
      ref="input"
      icon="ios-color-wand"
      @on-click="open"
    />
  </div>
</template>
<script lang="ts">
import { Input } from 'view-design';
import { Tsrv, T_srv, ifs, ts, vue } from '@/services';

@T_srv.comp
export default class oAuxInput extends vue {
  public compName: string = 'oAuxInput';

  @T_srv.prop() renderOpts: any;

  @T_srv.prop() params: any;

  private value = null;

  private startValue = null;

  private align = 'left';

  private auxProp = null;

  @T_srv.watch('params')
  onParamsChange() {
    this.initProps();
    this.setValue();
  }

  mounted() {
    this.initProps();
    this.setValue();
  }

  private initProps() {
    if (this.params.property) {
      const items = this.params.$form.items;
      const find = Tsrv.utils.find(
        items,
        el => el.field === this.params.property
      );
      if (find) {
        this.align = find.align || 'left';
      }
    } else {
      this.align = this.params.column.align || 'left';
    }
  }

  private open() {
    Tsrv.utils
      .createModal('o-aux-panel', {
        funName: this.renderOpts.props.funName,
        field: this.params.property || this.params.column.property,
        row: this.params.row || this.params.data,
        options: {
          column: this.renderOpts.props.inputColumn
        }
      })
      .then(data => {
        if (data) {
          this.setTableValue(data);
          this.setValue(data);
          this.emitEvent('dochange');
        }
      });
  }

  public resetValue() {
    this.setValue(null);
    this.setTableValue(null);
  }

  public setValue(val: null | string | undefined = undefined) {
    if (this.params.property) {
      this.value =
        val !== undefined ? val : this.params.data[this.params.property];
    } else if (this.params.column) {
      this.value =
        val !== undefined ? val : this.params.row[this.params.column.property];
    }
  }

  public setTableValue(val: string | null) {
    if (this.params.property) {
      this.params.data[this.params.property] = val === '' ? null : val;
    } else {
      this.params.row[this.params.column.property] = val === '' ? null : val;
    }
  }

  public getValue() {
    return this.params.property
      ? this.params.data[this.params.property]
      : this.params.row[this.params.column.property];
  }

  public emitEvent(event: string) {
    const ev = this.renderOpts.events;
    // 深拷贝有问题
    // const params = Tsrv.utils.clone(this.params);
    const params = Tsrv.utils.cloneNoMatchVue(this.params, true);
    params.from = 'inputtext';
    for (const action in ev) {
      if (ev[action] && action === `on-${event}`) {
        ev[action](params);
      }
    }
  }
}
</script>
